package com.atguigu.tingshu.album.receive;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author zlq
 * @CreateTime 2025/3/3
 */
@Component
public class TrackReceiver {
    @Resource
    private TrackInfoService trackInfoService;

    @Resource
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings =@QueueBinding(
            exchange=@Exchange(value= MqConst.EXCHANGE_TRACK),
            value=@Queue(value=MqConst.QUEUE_TRACK_STAT_UPDATE,autoDelete = "false",durable = "true"),
            key=MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(String msg, Message message, Channel channel){
        //1、判断消息是否成功发送
        if (!StringUtils.isEmpty(msg)) {
            //转换类型 string-》TrackStatMqVo
            TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
            //2、使用businessNo 属性去重，防止消息重复消费！
            String businessNo = trackStatMqVo.getBusinessNo();
            Boolean result = redisTemplate.opsForValue().setIfAbsent("trackStat:" + businessNo, businessNo, 10, TimeUnit.MINUTES);

            if (result) {
                try {
                    //3、调用服务
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    //5、消费消息失败，删除缓存的key，否则会无法消费重发的消息
                    this.redisTemplate.delete("trackStat:" + businessNo);
                    //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                    throw new RuntimeException(e);
                }
            }

        }

        //4、手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
